<template>
  <canvas ref="canvasRef" class="scene-canvas" />
</template>

<script setup lang="ts">
import * as THREE from 'three'
import { useWindowSize } from '@vueuse/core'
const { width, height } = useWindowSize()
import { threeTool, LightClass } from '@/utils/threeClass'
const canvasRef = ref()
const web3Dtool = new threeTool()
const lightTool = new LightClass()
import img3 from '@/assets/img/brick_roughness.jpg'
import disc from '@/assets/img/disc.png'

function createShaderMaterial() {
  // 顶点着色器代码
  const vertexShader = `
  uniform float uTime;
  uniform float uWaveHeight;
  uniform float uWaveFrequency;

  varying vec2 vUv;
  varying float vElevation;

  void main() {
    vUv = uv;

    // 计算波浪位移
    float elevation = sin(position.x * uWaveFrequency + uTime) *
                     cos(position.z * uWaveFrequency + uTime) *
                     uWaveHeight;

    vElevation = elevation;

    vec3 newPosition = position + normal * elevation;

    gl_Position = projectionMatrix * modelViewMatrix * vec4(newPosition, 1.0);
  }
`

  // 片元着色器代码
  const fragmentShader = `
  uniform float uTime;
  uniform vec3 uWaterColor;
  uniform vec3 uFoamColor;
  uniform sampler2D uNormalMap;

  varying vec2 vUv;
  varying float vElevation;

  void main() {
    // 法线贴图
    vec3 normalMap = texture2D(uNormalMap, vUv + uTime * 0.1).rgb;

    // 基于高度的颜色混合
    vec3 baseColor = mix(uWaterColor, uFoamColor, vElevation * 2.0);

    // 添加光照效果（简单版）
    vec3 lightDir = normalize(vec3(0.5, 1.0, 0.5));
    float diffuse = max(dot(normalMap, lightDir), 0.2);

    vec3 finalColor = baseColor * diffuse;

    gl_FragColor = vec4(finalColor, 0.9);
  }
`

  // 创建水面材质
  const waterMaterial = new THREE.ShaderMaterial({
    uniforms: {
      uTime: { value: 0 },
      uWaveHeight: { value: 0.2 },
      uWaveFrequency: { value: 2.0 },
      uWaterColor: { value: new THREE.Color(0x1e90ff) },
      uFoamColor: { value: new THREE.Color(0xffffff) },
      uNormalMap: {
        value: new THREE.TextureLoader().load(disc)
      }
    },
    vertexShader,
    fragmentShader,
    transparent: true,
    side: THREE.DoubleSide
  })
  // 添加错误检查
  waterMaterial.onBeforeCompile = shader => {
    console.log('Vertex Shader:', shader.vertexShader)
    console.log('Fragment Shader:', shader.fragmentShader)
  }

  // 创建水面几何体
  const waterGeometry = new THREE.PlaneGeometry(20, 20, 128, 128)
  const waterMesh = new THREE.Mesh(waterGeometry, waterMaterial)
  waterMesh.rotation.x = -Math.PI / 2
  web3Dtool.scene.add(waterMesh)
   // 添加动画循环
  function animate() {
    requestAnimationFrame(animate)

    // 更新水面材质的 uTime
    if (web3Dtool.scene && web3Dtool.scene.children.length > 0) {
      const waterMesh = web3Dtool.scene.children.find((child: { material: { uniforms: { uTime: any } } }) =>
        child.material && child.material.uniforms && child.material.uniforms.uTime
      )
      if (waterMesh) {
        waterMesh.material.uniforms.uTime.value += 0.01
      }

      // 更新全息投影材质的 uTime
      const hologramMesh = web3Dtool.scene.children.find((child: { material: { uniforms: { uTime: any } } }) =>
        child.material && child.material.uniforms && child.material.uniforms.uTime &&
        child !== waterMesh
      )
      if (hologramMesh) {
        hologramMesh.material.uniforms.uTime.value += 0.01
      }
    }
  }

  animate()
}

/**
 * @name 全息投影样例
 */
function createHologram() {
  // 全息效果着色器材质
  const hologramMaterial = new THREE.ShaderMaterial({
    uniforms: {
      uTime: { value: 0 },
      uScanSpeed: { value: 2.0 },
      uScanColor: { value: new THREE.Color(0x00ffff) },
      uBaseColor: { value: new THREE.Color(0x0088ff) }
    },

    vertexShader: `
    varying vec2 vUv;
    varying vec3 vPosition;

    void main() {
      vUv = uv;
      vPosition = position;
      gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
    }
  `,

    fragmentShader: `
    uniform float uTime;
    uniform float uScanSpeed;
    uniform vec3 uScanColor;
    uniform vec3 uBaseColor;

    varying vec2 vUv;
    varying vec3 vPosition;

    void main() {
      // 扫描线效果
      float scanLine = sin(vPosition.y * 20.0 - uTime * uScanSpeed) * 0.5 + 0.5;
      scanLine = pow(scanLine, 3.0); // 增强对比度

      // 边缘光效果
      float edgeGlow = 1.0 - smoothstep(0.0, 0.1, abs(vUv.x - 0.5) * 2.0);
      edgeGlow *= 1.0 - smoothstep(0.0, 0.1, abs(vUv.y - 0.5) * 2.0);

      // 颜色合成
      vec3 color = mix(uBaseColor, uScanColor, scanLine);
      color += edgeGlow * uScanColor * 0.5;

      // 透明度渐变
      float alpha = 0.6 + scanLine * 0.4;

      gl_FragColor = vec4(color, alpha);
    }
  `,

    transparent: true,
    side: THREE.DoubleSide,
    blending: THREE.AdditiveBlending
  })

  // 应用到的模型
  const model = new THREE.Mesh(
    new THREE.TorusGeometry(2, 0.5, 16, 100),
    hologramMaterial
  )
  web3Dtool.scene.add(model)
}
onMounted(() => {
  web3Dtool.setCanvasMain({ bgColor: 0x000000, canvasEl: canvasRef.value })
  web3Dtool.initScene()
  web3Dtool.animateFun()

  // createShaderMaterial()
})

// 5. 监听窗口大小变化
watch([width, height], e => {
  web3Dtool.watchUpdate(e[0], e[1])
})
</script>
<style scoped lang="scss">
.scene-canvas {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  outline: none;
}
</style>
